package com.avery.action;


import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.avery.dao.IDocumentDao;
import com.avery.dao.IDocumentLibraryDao;
import com.avery.dao.IUserDao;
import com.avery.dao.IUserRelationshipDao;
import com.avery.entity.Documentlibrary;
import com.avery.entity.User;
import com.avery.entity.Userrelationship;
import com.avery.util.ContextUtil;
import com.google.gson.Gson;

public class UserController extends MultiActionController {
	
	private static IUserDao userDao = null;
	private static IUserRelationshipDao userRelationshipDao = null;
	private static IDocumentLibraryDao documentLibraryDao = null;
	static{
		//获取Spring容器
		ApplicationContext aContext = ContextUtil.getContext();
		
		if(userDao == null){
			userDao = (IUserDao)aContext.getBean(IUserDao.class);
		}
		
		if(documentLibraryDao == null){
			documentLibraryDao = (IDocumentLibraryDao)aContext.getBean(IDocumentLibraryDao.class);
		}
		
		if(userRelationshipDao == null){
			userRelationshipDao = (IUserRelationshipDao)aContext.getBean(IUserRelationshipDao.class);
		}
	}
	
	public void checkUserName(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String msg = "";//用于存储返回值
		response.setCharacterEncoding("utf-8");
		String locUsername = request.getParameter("username");
		//取出数据
		User locUser = userDao.findByName(locUsername);
		if(locUser == null){
			//如果找到未此条用户名，则可注册
			msg = "success";
		}else{
			msg = "failed";
		}
		
		//将信息发送至界面
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print(msg);
		out.flush();
		out.close();
	}
	
	public ModelAndView registerAction(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//设置返回与跳转的信息
		Map<String, String> skipInfo = new HashMap<String, String>();
		//获取用户提交的用户信息
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		
		if((!"".equals(userName))&&(!"".equals(password))&&(!"".equals(email))){
			//当用户名、密码和email都不为空时，注册此用户
			User user = new User();
			user.setUsername(userName);
			user.setPassword(password);
			user.setEmail(email);
			user.setBirthplace(0);
			user.setEducationlevel(0);
			user.setIsactive(0);
			user.setLocalplace(0);
			user.setSex(0);
			user.setAge(20);
			user.setIdentity(0);
			//注册用户信息于数据库
			userDao.insert(user);
			//添加库时为每个用户添加一个分享库
			Documentlibrary shareLibrary = new Documentlibrary();
			shareLibrary.setBelonguser(userDao.findByName(userName).getUid());
			shareLibrary.setLibraryname("分享库");
			documentLibraryDao.insert(shareLibrary);
			
			skipInfo.put("showInfo", "注册成功！");
			skipInfo.put("skipPage", "login.jsp");
		}else{
			skipInfo.put("showInfo", "注册失败！");
			skipInfo.put("skipPage", "register.jsp");
		}
		
		return new ModelAndView("result", "skipInfo",skipInfo);//\\TODO:Should go to login page
	}
	
	public String loginAction(HttpServletRequest request,HttpServletResponse response) throws Exception{

		//获取用户提交的用户信息
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		
		
		if((!"".equals(userName))&&(!"".equals(password))){
			//当用户名、密码和email都不为空时，验证此用户信息
			User targetUser = userDao.findByName(userName);
			if(targetUser != null){
				if(targetUser.getPassword().equals(password)){
					//登录成功
					request.getSession().setAttribute("username", userName);
					
					//登录成功时将用户的好友列表取出来			
					request.getSession().setAttribute("locUserFriends", userDao.getAllFriendsWithUsername(userName));
					
					return "../welcome";//TODO:Should go to home
				}
			}
		}
		//设置返回与跳转的信息
		Map<String, String> skipInfo = new HashMap<String, String>();
		skipInfo.put("showInfo", "登录失败！");
		skipInfo.put("skipPage", "login.jsp");
		request.setAttribute("skipInfo",skipInfo);
		return "result";//\\TODO:Should go to login page
		
	}
	
	public String updateAction(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
	
		return null;//TODO:Should go to show info
	}
	
	public ModelAndView showUserInfoAction(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		//获取Spring容器
		//ApplicationContext aContext = ContextUtil.getContext();
	
		//设置响应类型
		response.setContentType("text/xml");
		//设置文本编码
		request.setCharacterEncoding("utf-8");
		
		
		return new ModelAndView("../welcome");
		//return null;//TODO:Should go to show info page
	}
	
	public ModelAndView quitUserAction(HttpServletRequest request,HttpServletResponse response) throws Exception{
		System.out.println("go to quit!!!");
		//获取当前网页session
		HttpSession session=request.getSession();
		session.removeAttribute("username");
		session.removeAttribute("check");
		
		return new ModelAndView("../welcome");
	}
	
	public void addFriendAction(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String msg = "";//用于存储返回值
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String locUsername = session.getAttribute("username").toString();
		String locFriendname = request.getParameter("friendname");
		//取出数据
		User locUser = userDao.findByName(locUsername);
		User friend = userDao.findByName(locFriendname);
		if(locUsername.equals(locFriendname)){
			msg = "这是你自己！";
		}else{
			if(friend != null){
				//添加关系表数据
				Userrelationship userRelation = new Userrelationship();
				userRelation.setUserid(locUser.getUid());
				userRelation.setFriendid(friend.getUid());
				//如果之前未添加过此条好友，则插入
				if(userRelationshipDao.findByUserIDAndFriendID(userRelation) == null){
					userRelationshipDao.insert(userRelation);
					msg = "success";
				}else{
					msg = "已经是你的好友了！";
				}
			}else{
				msg = "can't not get friend value";
			}
		}
		//将信息发送至界面
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print(msg);
		out.flush();
		out.close();
	}
	
	public void deleteFriendAction(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String msg = "";//用于存储返回值
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String locUsername = session.getAttribute("username").toString();
		String locFriendname = request.getParameter("friendname");
		//取出数据
		User locUser = userDao.findByName(locUsername);
		User friend = userDao.findByName(locFriendname);
		if(friend != null){
			//添加关系表数据
			Userrelationship userRelation = new Userrelationship();
			userRelation.setUserid(locUser.getUid());
			userRelation.setFriendid(friend.getUid());
			
			Userrelationship relationshipFromDB = userRelationshipDao.findByUserIDAndFriendID(userRelation);
			if(relationshipFromDB == null){
				System.out.println("未找到此条关系记录在数据库");
			}else{
				//删除此条关系记录
				userRelationshipDao.deleteByID(relationshipFromDB.getId());
				msg = "success";
			}
		}else{
			msg = "can't not get friend value";
		}
		
		//将信息发送至界面
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print(msg);
		out.flush();
		out.close();
	}
	
	public void showAllFriend(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String userStr = "";//用于存储查询出来的文档信息
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String locUsername = session.getAttribute("username").toString();
		//取出数据
		List<User> friendList = userDao.getAllFriendsWithUsername(locUsername);
		if(friendList != null){
			Gson gson = new Gson();
			userStr = gson.toJson(friendList);
		}
		
		//将信息发送至界面
		PrintWriter out = response.getWriter();	
		out.println("{\"page\":"+1+",\"total\":"+friendList.size()+",\"rows\":" +userStr+"}");
		out.flush();
		out.close();
	}
	
	
	
	
}
